<template>
    <!-- 组件容器 -->
    <div class="stock-list-container">
        <!-- 操作容器 -->
        <div class="stock-list-options flex" style="height: 50px; width: 400px">
            <el-autocomplete
                class="inline-input w-50"
                v-model="searchValue"
                :fetch-suggestions="querySearch"
                placeholder="请选择库存纸尺寸(2222*333)"
                @select="handleSelect"
                @input="handleInput"
                @clear="clearSelect"
                clearable
            />
            <el-button class="ml-2" :icon="Refresh" @click="getStockListEvent">刷新</el-button>
        </div>
        <!-- 库存列表 -->
        <div v-if="stockList.length > 0" class="stock-list-descriptions">
            <!-- 滚动条 -->
            <el-scrollbar height="calc(100vh - 150px)">
                <!-- 库存纸列表 -->
                <el-descriptions title="库存：" border :column="4" v-for="(item, index) in stockList" :key="index" class="mb-4">
                    <el-descriptions-item label="面纸规格">
                        <el-text type="primary">{{ item.tissueSize ? item.tissueSize : '/' }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="瓦纸规格">
                        <el-text type="primary">{{ item.corrugatedSize ? item.corrugatedSize : '/' }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="材质">
                        <el-text type="primary">{{ item.materialQuality }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="压线">
                        <el-text type="primary">{{ item.crimping ? item.crimping : '/' }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="采购量">
                        <el-text type="primary">{{ item.purchaseNumber }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="使用量">
                        <el-text type="primary">{{ item.makeNumber }}</el-text>
                    </el-descriptions-item>
                    <el-descriptions-item label="库存分销" :span="2">
                        <div class="flex items-center">
                            <!-- 弹出框 -->
                            <el-popover :width="600">
                                <!-- 触发 Popover 显示的 HTML 元素 -->
                                <template #reference>
                                    <svg
                                        t="1747274520245"
                                        class="icon"
                                        viewBox="0 0 1024 1024"
                                        version="1.1"
                                        xmlns="http://www.w3.org/2000/svg"
                                        p-id="2111"
                                        width="25"
                                        height="25"
                                    >
                                        <path
                                            d="M872.5504 652.3904v-56.6272c0-45.6192-43.8272-82.7392-97.792-82.7392h-234.8544v-51.2a191.0784 191.0784 0 1 0-51.2 0v51.2H253.9008c-53.9648 0-97.792 37.12-97.792 82.7392v55.8592a140.2368 140.2368 0 1 0 51.2-2.56v-53.2992c0-17.1008 21.2992-31.5392 46.592-31.5392h234.8032V650.24a140.2368 140.2368 0 1 0 51.2 0v-86.016h234.8544c25.2928 0 46.592 14.4384 46.592 31.5392v52.8896a140.1856 140.1856 0 1 0 51.2 3.7376zM374.4256 272.3328a139.9296 139.9296 0 1 1 139.8784 139.8784 140.0832 140.0832 0 0 1-139.8784-139.8784zM277.6064 787.968a89.0368 89.0368 0 1 1-89.0368-88.9856 89.088 89.088 0 0 1 89.0368 88.9856z m325.7344 0a89.0368 89.0368 0 1 1-89.0368-88.9856 89.088 89.088 0 0 1 89.0368 88.9856z m233.5232 88.9856a88.9856 88.9856 0 1 1 89.0368-88.9856 89.088 89.088 0 0 1-89.0368 88.9856z"
                                            fill="#659ae8"
                                            p-id="2112"
                                        ></path>
                                    </svg>
                                </template>
                                <!-- Popover 内嵌 HTML 文本 -->
                                <template #default>
                                    <div class="flex gap-4 flex-col">
                                        <div class="flex justify-between" v-for="(i, j) in item.makeItems" :key="j">
                                            <div>
                                                <el-text type="info">{{ j + 1 }}. </el-text>
                                                <el-text type="warning">{{ i.productName }}</el-text>
                                                <el-text type="primary"> * </el-text>
                                                <el-text type="warning">{{ i.purchaseNumber }}只 </el-text>
                                            </div>
                                            <el-text type="primary">分销时间：{{ dayjs(i.createdAt).format('YYYY-MM-DD') }}</el-text>
                                        </div>
                                    </div>
                                </template>
                            </el-popover>
                            <el-button type="primary" class="ml-4" plain @click="initLimitData(item)">分销库存</el-button>
                            <el-button type="danger" class="ml-4" plain @click="destroyData(item)">库存销毁</el-button>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="库存备注" :span="4">
                        <el-input v-model="item.stockRemark" :rows="3" type="textarea" @change=""></el-input>
                        <el-button type="primary" class="mt-2" @click="">保存</el-button>
                    </el-descriptions-item>
                </el-descriptions>
            </el-scrollbar>
        </div>
        <!-- 无库存纸提示 -->
        <div v-else>
            <el-empty description="暂无库存纸" />
        </div>
    </div>
    <!-- 分销库存dialog -->
    <Distribution v-model:distribution-visible="distributionVisible" v-model:limit-data="limitData" :stock-info="stockInfo"></Distribution>
</template>

<script setup lang="ts">
import { destroyStock, getStockList } from '@/api/process';
import { Refresh } from '@element-plus/icons-vue';
import Distribution from './components/Distribution.vue';
import dayjs from 'dayjs';

onMounted(() => {
    getStockListEvent();
});

/* ******************************通用属性/方法****************************** */
// 缓存
const cache: AjaxResponse['stockList'] = [];
// 库存纸数据
const stockList = reactive<AjaxResponse['stockList']>([]);
// 加载所有库存纸
const getStockListEvent = async () => {
    // 清空数据
    stockList.length = 0;
    // 获取所有库存纸
    const result = await getStockList();
    result.data.forEach((item) => {
        item.value = item.tissueSize ? item.tissueSize : item.corrugatedSize;
        stockList.push(item);
        cache.push(item);
    });
};

/* ******************************搜索属性/方法****************************** */
// 搜索值
const searchValue = ref('');
// 搜索数据
const querySearch = (queryString: string, cb: any) => {
    // 搜索方法
    const results = queryString ? stockList.filter(createFilter(queryString)) : stockList;
    // call callback function to return suggestions
    cb(results);
};
// 搜索数据的过滤方法
const createFilter = (queryString: string) => {
    return (restaurant: AjaxResponse['stockList'][0]) => {
        // 准备对比数据
        const comparison = Number(queryString);
        let pre = 0;
        let next = 0;
        let _pre = 0;
        let _next = 0;

        // 如果存在面纸
        if (restaurant.tissueSize !== '') {
            pre = Number(restaurant.tissueSize.split('*')[0]);
            next = Number(restaurant.tissueSize.split('*')[1]);
        }

        // 如果存在瓦楞
        if (restaurant.corrugatedSize !== '') {
            _pre = Number(restaurant.corrugatedSize.split('*')[0]);
            _next = Number(restaurant.corrugatedSize.split('*')[1]);
        }

        // 搜索值小于等于库存纸规格
        if (pre >= comparison || next >= comparison || _pre >= comparison || _next >= comparison) {
            return true;
        }
        return false;
    };
};
// 搜索数据选择展示
const handleSelect = (item: any) => {
    // 清空数据
    stockList.length = 0;
    // 缓存数据并填充选中的数据展示
    for (let index = 0; index < cache.length; index++) {
        const i = cache[index];
        // 如果匹配到数据，则填充数据并返回
        if (i.corrugatedSize == item.corrugatedSize && i.tissueSize == item.tissueSize) {
            stockList.push(i);
            return;
        }
    }
};
// 清除输入框
const clearSelect = () => {
    // 清空数据
    stockList.length = 0;
    // 缓存数据并填充所有的数据
    stockList.push(...cache);
};
// 处理输入框的blur事件
const handleInput = (value: string) => {
    if (value == '') {
        clearSelect();
    }
};

/* ******************************描述列表属性/方法****************************** */

/* ******************************分销库存属性/方法****************************** */
// 定义limitDta接口
interface LimitData {
    length: number;
    width: number;
}
// 分销库存dialog
const distributionVisible = ref(false);
watch(
    () => distributionVisible.value,
    (newValue) => {
        // 当dialog关闭时，重新加载数据
        if (!newValue) {
            getStockListEvent();
        }
    }
);
// 分销库存dialog数据
const limitData = reactive<LimitData>({ width: 0, length: 0 });
// 传入的库存纸大小
const stockInfo = reactive({
    _id: '',
    size: '',
    crimping: '',
    materialQuality: '',
    remainingNumber: 0,
});
// 打开dialog前数据加载
const initLimitData = (item: AjaxResponse['stockList'][0]) => {
    // 获取纸张规格和压线
    const size = item.tissueSize ? item.tissueSize : item.corrugatedSize;
    stockInfo._id = item._id;
    stockInfo.size = size;
    stockInfo.crimping = item.crimping;
    stockInfo.materialQuality = item.materialQuality;
    stockInfo.remainingNumber = item.purchaseNumber - item.makeNumber;
    // 获取纸张尺寸
    const [length, width] = size.split('*');
    // 赋值
    limitData.length = Number(length);
    limitData.width = Number(width);
    // 打开dialog
    distributionVisible.value = true;
};

// 销毁库存
const destroyData = (item: AjaxResponse['stockList'][0]) => {
    // 确认销毁
    ElMessageBox.confirm('确认销毁该库存吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        // 调用销毁库存接口
        const result = await destroyStock(item._id);
        if (result.code == 200) {
            // 销毁成功后，刷新数据
            getStockListEvent();
            // 提示用户
            ElMessage.success('销毁成功');
        } else {
            ElMessage.error(result.msg);
        }
    });
};
</script>

<style scoped lang="scss">
.stock-list-container {
    height: calc(100vh - 100px);
    width: 100%;
    overflow: auto;
}
</style>
